package com.ljc.common.exception;

import cn.hutool.json.JSONUtil;
import com.ljc.common.lang.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 * @Author: ljc
 * @Date:Created in 13:43 2022/2/14
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView handler(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
        //ajax处理
        String header = request.getHeader("X-Requested-With");
        if (header != null && "X-Requested-With".equals(header)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSONUtil.toJsonStr(Result.fail(exception.getMessage())));
            return null;
        }
        if (exception instanceof NullPointerException) {
            //...
        }
        //web处理
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("message", exception.getMessage());
        return modelAndView;
    }
}
